package mytomcat.servlet.base;

import mytomcat.core.MyRequest;
import mytomcat.core.MyResponse;
import mytomcat.dto.ServletInfo;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * <ul>
 * <li>Title:MyServlet</li>
 * <li>Description: TODO </li>
 * <li>Copyright: Copyright (c) 2018</li>
 * </ul>
 *
 * @author swc
 * @version     V1.0
 * @date 2020/4/20 0020 上午 9:54
 */
public abstract class MyServlet {

    public abstract  void doGet(MyRequest myRequest, MyResponse myResponse, ServletInfo servletInfo);

    public abstract  void doPost(MyRequest myRequest, MyResponse myResponse, ServletInfo servletInfo);


    public  void service(MyRequest myRequest, MyResponse myResponse, ServletInfo servletInfo){
        if("POST".equalsIgnoreCase(myRequest.getMethod())){
            doPost(myRequest,myResponse,servletInfo);
        }else if("GET".equalsIgnoreCase(myRequest.getMethod())){
            doGet(myRequest,myResponse,servletInfo);
        }
    }


    protected void doHand(MyRequest myRequest,MyResponse myResponse,ServletInfo servletInfo) {
        String viewRoot ="\\src"+servletInfo.getViewPrefix();
        try {
            String root =System.getProperty("user.dir");
            viewRoot = root.split("src\\\\main\\\\java")[0]+viewRoot;

            FileInputStream fileInputStream = new FileInputStream(viewRoot+servletInfo.getViewName()+servletInfo.getViewSuffix());
            StringBuffer sbf = new StringBuffer();
            byte[] buf = new byte[1024];
            int length = 0;
            while((length = fileInputStream.read(buf)) != -1){
                sbf.append(new String(buf,0,length));
            }
            //最后记得，关闭流
            fileInputStream.close();
            myResponse.write(sbf.toString().replace("${ctx}","http://localhost:"+myRequest.getPort()),servletInfo.getContentType());
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

}
